package com.lds.config.center.server.mcp.controller;

import com.lds.config.center.server.mcp.model.*;
import com.lds.config.center.server.mcp.server.EnvMcpServer;
import com.lds.config.center.server.mcp.model.business.GetEnvMcpResponse;
import com.lds.management.center.common.model.dto.ResultDTO;
import com.lds.management.center.common.util.JsonUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@Slf4j
@RestController
@RequestMapping("/mcp")
@RequiredArgsConstructor
public class McpServerController {
    private final EnvMcpServer envMcpServer;

    @PostMapping("/common")
    public ResponseEntity<McpResponse> common(@RequestBody McpRequest request) {
        try {
            McpResponse response = new McpResponse();
            response.setId(request.getId());
            response.setJsonrpc("2.0");

            switch (request.getMethod()) {
                case "initialize":
                    response.setResult(handleInitialize(request.getParams()));
                    break;
                case "tools/list":
                    response.setResult(handleToolsList(request.getParams()));
                    break;
                case "tools/call":
                    response.setResult(handleToolsCall(request.getParams()));
                    break;
                default:
                    McpError error = new McpError();
                    error.setCode(-32601);
                    error.setMessage("Method not found: " + request.getMethod());
                    response.setError(error);
            }

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Error handling MCP request", e);
            McpResponse errorResponse = new McpResponse();
            errorResponse.setId(request.getId());
            McpError error = new McpError();
            error.setCode(-32603);
            error.setMessage("Internal error: " + e.getMessage());
            errorResponse.setError(error);
            return ResponseEntity.ok(errorResponse);
        }
    }

    private Object handleInitialize(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        result.put("protocolVersion", "2025-06-18");
        result.put("capabilities", getServerCapabilities());
        result.put("serverInfo", getServerInfo());
        return result;
    }

    private Map<String, Object> getServerCapabilities() {
        Map<String, Object> capabilities = new HashMap<>();

        // 资源能力
        Map<String, Object> resources = new HashMap<>();
        resources.put("listChanged", false);
        resources.put("subscribe", false);
        capabilities.put("resources", resources);

        // 工具能力
        Map<String, Object> tools = new HashMap<>();
        tools.put("listChanged", true);
        capabilities.put("tools", tools);

        // 采样器能力
        Map<String, Object> samplers = new HashMap<>();
        samplers.put("listChanged", false);
        capabilities.put("samplers", samplers);

        return capabilities;
    }

    private Map<String, Object> getServerInfo() {
        Map<String, Object> serverInfo = new HashMap<>();
        serverInfo.put("name", "config-center-mcp-server");
        serverInfo.put("version", "1.0.0");
        return serverInfo;
    }

    private Object handleToolsList(Map<String, Object> params) {
        // 实现工具列表逻辑
        List<ToolDefinition> tools = new ArrayList<>();

        // env tool
        ToolDefinition envTool = new ToolDefinition();
        envTool.setName("getEnv");
        envTool.setDescription("根据环境名称获取环境信息");

        InputSchema inputSchema = new InputSchema();
        Map<String, InputSchema.Property> properties = new HashMap<>();
        properties.put("envName", new InputSchema.Property("string", "环境名称"));
        inputSchema.setProperties(properties);
        inputSchema.setRequired(Collections.singletonList("envName"));
        envTool.setInputSchema(inputSchema);
        tools.add(envTool);

        Map<String, Object> map = new HashMap<>();
        map.put("tools", tools);
        return map;
    }

    private Object handleToolsCall(Map<String, Object> params) {
        String name = (String) params.get("name");
        Map<String, Object> arguments = (Map<String, Object>) params.get("arguments");

        // 根据工具名称调用相应的工具
        if (name.equals("getEnv")) {
            return handleEnvTool(arguments);
        }
        throw new RuntimeException("Unknown tool: " + name);
    }

    private Object handleEnvTool(Map<String, Object> arguments) {
        String envName = (String) arguments.get("envName");
        ResultDTO<GetEnvMcpResponse> resultDTO = envMcpServer.getEnv(new GetEnvMcpRequest(envName));
        return new ToolCallResult(new ToolCallResult.ContentItem(JsonUtil.toJson(resultDTO)));
    }
}
